package router

import (
	"fmt"
	"time"

	"github.com/gin-contrib/cors"
	ginzap "github.com/gin-contrib/zap"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"gin-scaffold/setting"
)

func Setup() *gin.Engine {
	gin.SetMode(setting.Conf.Mode)

	r := gin.New()
	// 注册中间件
	r.Use(ginzap.Ginzap(zap.L(), time.RFC3339, true), ginzap.RecoveryWithZap(zap.L(), true))

	// CORS
	r.Use(CorsHandler())

	apiGroup := r.Group(fmt.Sprintf("api/%s", setting.Conf.Version))
	PingRouter(apiGroup)
	UserRouter(apiGroup)

	return r
}

// CorsHandler resolve cors.
func CorsHandler() gin.HandlerFunc {
	config := cors.DefaultConfig()
	conf := setting.Conf.CorsConfig
	if conf.AllowAllOrigins || len(conf.AllowOrigins) == 0 {
		config.AllowAllOrigins = true
	} else {
		config.AllowOrigins = conf.AllowOrigins
	}
	config.AddAllowHeaders(conf.AllowHeaders...)
	config.AddExposeHeaders(conf.ExposeHeaders...)
	return cors.New(config)
}
